// pages/exercise/rank.js
const db = wx.cloud.database()
var exercise_id

Page({

  /**
   * 页面的初始数据
   */
  data: {
    exercise: null,
    userInfo: null,
    userTest: null,
    list: [],
    rank: 0,
    nomore: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    exercise_id = options.exercise_id
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    //查询每日一练
    db.collection('exercise').doc(exercise_id).get({
      success: res => {
        that.setData({
          exercise: res.data
        })
      }
    })
    var openid = wx.getStorageSync('openid')
    if(!openid){
      wx.redirectTo({
        url: '../index/welcome',
      })
      return false
    }
    //查询用户信息
    db.collection('userInfo').where({
      _openid: openid
    }).get({
      success: res => {
        that.setData({
          userInfo: res.data[0]
        })
      }
    })
    //查询用户测试
    db.collection('userTest').where({
      _openid: openid,
      exercise_id
    }).get({
      success: res => {
        if(res.data.length){
          that.setData({
            userTest: res.data[0]
          })
        }else{
          wx.redirectTo({
            url: '../index/welcome',
          })
        }
      }
    })
    //查询排名
    const _ = db.command
    db.collection('userTest').where({
      exercise_id,
      add_time : _.gt(new Date("2020/12/22 13:30:00"))
    }).orderBy('corrects','desc',).orderBy('seconds', 'asc').limit(99).get({
      success: res => {
        var list = res.data
        var rank = ''
        list.forEach(function(item,index){
            db.collection('userInfo').where({
              _openid: item._openid
            }).get({
              success: res => {
                list[index].i = index + 1
                if(openid == item._openid){
                  rank = index + 1
                }
                list[index].nickName = res.data[0].nickName
                list[index].avatarUrl = res.data[0].avatarUrl
              }
            })
        })
        
        setTimeout(function(){
          if(rank == ''){
            rank = '20+'
          }
          that.setData({
            list,
            rank,
            nomore: true
          })
        },5000)
          
        
        
      }
      
    })
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})